package com.egg.ylt.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.egg.ylt.MainActivity;
import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.activity.ACT_ShopDetail;
import com.egg.ylt.activity.ACT_SwitchBaby;
import com.egg.ylt.activity.ACT_UserLogin;
import com.egg.ylt.pojo.TabEntity;
import com.egg.ylt.pojo.UploadPhotoEntity;
import com.egg.ylt.presenter.impl.FraHealthImpl;
import com.egg.ylt.uploadingphoto.UriUtils;
import com.egg.ylt.view.IHealthView;
import com.yonyou.framework.library.base.BaseFragment;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;
import com.yonyou.framework.library.common.utils.ScreenUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;
import com.yonyou.framework.library.eventbus.EventCenter;
import com.yonyou.framework.library.widgets.tablayout.CommonTabLayout;
import com.yonyou.framework.library.widgets.tablayout.CustomTabEntity;
import com.yonyou.framework.library.widgets.tablayout.OnTabSelectListener;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by sichaoqi on 2018/8/23.
 */

public class FRA_Health extends BaseFragment<FraHealthImpl> implements OnTabSelectListener {

    @BindView(R.id.health_fake_navi)
    CommonTabLayout health_nav;
    @BindView(R.id.iv_diary_health)
    ImageView ivDiaryHealth;
    @BindView(R.id.fragment_health)
    FrameLayout fragmentHealth;
    @BindView(R.id.linearLayout2)
    ConstraintLayout ll_top;

    private FRA_Record mRecord;
    private FRA_Swim mSwim;

    //fragment对象
    private Fragment currentFragment;

    //标记
    private ImageView ivCurrent;
    private TextView tvCurrent;


    // 拍照回传码
    public final static int CAMERA_REQUEST_CODE = 0;
    // 相册选择回传吗
    public final static int GALLERY_REQUEST_CODE = 1;
    //系统剪裁
    private final static int GO_TO_ZOOM = 3;
    private final static int GO_SWITCH_BABY = 4;
    // 拍照的照片的存储位置
    private String mTempPhotoPath;
    // 照片所在的Uri地址
    private Uri imageUri;

    //调用照相机返回图片文件
    private Uri imageCropUri;
    private AlertDialog mOpenCamersDialog;

    private String[] mTitles = {"记录", "游泳"};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {
    }

    @Override
    protected View getLoadingTargetView() {
        return fragmentHealth;
    }

    @Override
    protected void initViewsAndEvents() {
        //动态设置沉浸式状态栏的高度
        int statusBarHeight = ScreenUtil.getStatusBarHeight(mContext);
        health_nav.setPadding(0, statusBarHeight + health_nav.getPaddingTop(), 0, health_nav.getPaddingBottom());
        //初始化fragment
        mRecord = new FRA_Record();
        mSwim = new FRA_Swim();

        initTablyout();

        // 设置主页显示的页面
        if (!mRecord.isAdded()) {
            currentFragment = mRecord;
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            transaction.add(R.id.fragment_health, mRecord);
            //transaction.replace(R.id.fragment_health, mRecord);
            transaction.commitAllowingStateLoss();
        }

        //切换宝宝
        ivDiaryHealth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用动态获取权限
                if (Constants.TOKEN == null || "".equals(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                } else if ("".equals(Constants.BABYID)) {
                    CommonUtils.makeEventToast(getActivity(), "请先添加宝宝", false);
                } else {
                    Intent intent = new Intent(mContext, ACT_SwitchBaby.class);
                    startActivityForResult(intent, GO_SWITCH_BABY);
                }
            }
        });
    }

    private void initTablyout() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }
        health_nav.setTabData(mTabEntities);
        health_nav.setOnTabSelectListener(this);
        health_nav.setCurrentTab(0);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fra_health_rebuild;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }


    /**
     * 切换Fragment
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to) {
        if (currentFragment != to) {
            currentFragment = to;
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
//            transaction.replace(R.id.fragment_health, to);
//            transaction.commitAllowingStateLoss();

            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from).add(R.id.fragment_health, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }


    /**
     * 打开相机和相册的弹出框
     */
    public void OpenCameraDialog() {
        if (mOpenCamersDialog != null) {
            mOpenCamersDialog.dismiss();
        }
        mOpenCamersDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_open_camera)
                .fromBottom(true)
                .fullWidth()
                .setOnClickListener(R.id.tv_take_photos, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        takePhoto();
                    }
                })
                .setOnClickListener(R.id.tv_cancel_camera, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOpenCamersDialog.dismiss();
                    }
                })
                .show();
        TextView view = mOpenCamersDialog.getView(R.id.tv_photo_album);
        view.setVisibility(View.GONE);
    }

    /**
     * 拍照实现方法
     */
    private void takePhoto() {
        //打开相机后，关闭弹出框
        mOpenCamersDialog.dismiss();

        // 跳转到系统的拍照界面
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定照片存储位置为sd卡本目录下
        // 这里设置为固定名字 这样就只会只有一张temp图 如果要所有中间图片都保存可以通过时间或者加其他东西设置图片的名称
        // File.separator为系统自带的分隔符 是一个固定的常量
        mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
        // 获取图片所在位置的Uri路径    *****这里为什么这么做参考问题2*****
        /*imageUri = Uri.fromFile(new File(mTempPhotoPath));*/
        imageUri = FileProvider.getUriForFile(getActivity(), "com.egg.provider", new File(mTempPhotoPath));
        //下面这句指定调用相机拍照后的照片存储的路径
        intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intentToTakePhoto, CAMERA_REQUEST_CODE);
    }

    /**
     * 打开相册方法实现
     */
    private void choosePhoto() {
        //选择相册后，关闭弹出框
        mOpenCamersDialog.dismiss();

        Intent intentToPickPic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型" 所有类型则写 "image/*"
        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentToPickPic, GALLERY_REQUEST_CODE);
    }


    //把图片上传到服务器
    public void upLoad(Uri uri) {
        try {
            mPresenter.upLoadPhoto(UriUtils.getBitmapFormUri(getActivity(), uri, "photo"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        currentFragment.onHiddenChanged(hidden);
        EventBus.getDefault().post(new EventCenter(hidden ? Constants.CLEAR_SWIM_FRAGMENT : Constants.INIT_SWIM_FRAGMENT));
    }

    @Override
    public void onTabSelect(int position) {
        switch (position) {
            case 0:
                switchContent(currentFragment, mRecord);
                break;
            case 1:
                switchContent(currentFragment, mSwim);
                break;
        }
    }

    @Override
    public void onTabReselect(int position) {

    }
}
